<template>
	<view class="wrap">
		<!-- <text>123123</text> -->
		<view class="top">
			<u-form :model="form" :rules="rules" ref="uForm" label-width="180">
				<u-form-item label="姓名" prop="name">
					<u-input v-model="form.name" border placeholder="请填写姓名" />
				</u-form-item>
				<u-form-item label="性别" prop="sex">
					<u-radio-group v-model="form.sex" @change="radioGroupChange" active-color="#10beca">
						<u-radio @change="radioChange" v-for="(item, index) in radioList" :key="index"
							:name="item.value">
							<text class="u-font-28">{{item.label}}</text>
						</u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label="手机号码" prop="mobile">
					<u-input v-model="form.mobile" border placeholder="请填写手机号" />
				</u-form-item>
				<u-form-item label="所在地区" prop="selectArea">
					<view class="u-flex" style="width: 100%;">
						<view class="u-flex-1" @click="cityshow = true">
							<text v-if="form.selectArea">{{form.selectArea}}</text>
							<text v-else class="u-tips-color">请选择到街道级别</text>
						</view>
						<view @click="showmap = true" class="u-p-l-10 u-p-t-6" style="display: flex;align-items: center;">
							<u-icon name="map-fill" color="#10beca"></u-icon><text class="u-font-28 u-main-color u-p-l-5" style="color: #10beca;">定位</text>
						</view>
					</view>
				</u-form-item>
				<u-form-item label="详细地址" prop="address">
					<view class="textarea-box">
						<view class="address u-flex-1" @click="chooseMap">
							<u-input v-model="form.address" :disabled="form.address == ''?true:false" :border="true" type="textarea" placeholder="如阳光花园1号楼1单元301室"  @click="chooseMap"/>
						</view>
					</view>
				</u-form-item>
				<u-alert-tips v-if="addressId == 0" type="warning" title="请您尽量填写详细地址，以便成功回收" :show-icon="true"></u-alert-tips>
			</u-form>
		</view>

		<!-- 修改地址时才可以设置默认 -->
		<view class="bottom" v-if="addressId > 0">
			<view class="default">
				<view class="left">
					<view class="set">设置默认地址</view>
					<view class="tips">提醒：每次下单会默认推荐该地址</view>
				</view>
				<view class="right">
					<switch :checked="form.isdefault" @change="setDefault" />
				</view>
			</view>
		</view>

		<view class="u-p-30">
			<u-button type="primary" @click="onSubmit('edit')" v-if="isedit" :loading="loading">确定修改</u-button>
			<u-button type="primary" @click="onSubmit('add')" v-else :loading="loading">添加</u-button>
		</view>
		<view class="u-p-l-30 u-p-r-30 u-p-b-30" v-if="isedit">
			<u-button type="error" @click="del" :loading="loading">删除</u-button>
		</view>
		<view class="u-p-l-30 u-p-r-30 u-p-b-30">
			<u-button @click="back">返回</u-button>
		</view>
		<u-picker mode="region" ref="uPicker" v-model="show" />
		<!-- 选择所在地区 -->
		<citypicker ref="citypicker" :show="cityshow" :level="4" @select="getSelectCity" @close="close"></citypicker>
	</view>
</template>

<script>
	import {
		mapState,
		mapGetters,
		mapActions
	} from 'vuex';

	export default {
		name: 'address-add',
		props:{
			addressId: 0,
			type: '',
		},
		data() {
			return {
				edit:"",
				loading: false,
				isedit: false,
				cityshow: false,
				show: false,
				detailsAddress: '',
				form: {
					name: "",
					sex: 1,
					mobile: "",
					address: "",
					cityid: 0,
					lng: 0,
					lat: 0,
					selectArea: ''
				},
				rules: {
					name: [{
						required: true,
						message: '请输入姓名',
						trigger: 'change',
					}],
					mobile: [{
							required: true,
							message: '请填写手机号码',
							trigger: 'change'
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: 'blur',
						}
					],
					selectArea: [{
						required: true,
						message: '请选择所在地区',
						trigger: 'change'
					}],
					address: [{
						required: true,
						message: '请从地图中选择地址',
						trigger: 'change'
					}]
				},
				selectArea: '',
				// 选择定位
				showmap: false,
				chooseLocation:{
					name: '',
					address: '',
					latitude: 0,
					longitude: 0
				},
				radioList: [{
						label: '先生',
						value: 1,
						disabled: false
					},
					{
						label: '女士',
						value: 2,
						disabled: false
					},
				]
			};
		},
		computed: {
			...mapState({
				userdetail: state => state.userdetail,
				webSetting: state => state.webSetting
			})
		},
		mounted() {
			this.$refs.uForm.setRules(this.rules);
			if(this.addressId > 0){
				this.getDetails(this.addressId)
			}
			// 初始化地区（指定经营地区，从/Operator/Detail获取）
			// this.$store.dispatch('getWebSetting').then(res => { //获取网站信息
			// 	console.log('getWebSetting',res)
			// 	// this.setCity = res.city
			// 	// console.log('setCity',this.setCity)
				
			// 	// this.areaArr.push({
			// 	// 	id: this.setCity.cityid,
			// 	// 	name: this.setCity.cityname,
			// 	// 	level: 1
			// 	// })
			// 	// this.getNextAreaData(this.setCity.cityid)
			// })
		},
		watch:{
			showmap(val){
				console.log('点击展示地图')
				if(val){
					this.showmap = false
					uni.chooseLocation({
						success: (res)=> {
							console.log('位置名称：' + res.name);
							console.log('详细地址：' + res.address);
							console.log('纬度：' + res.latitude);
							console.log('经度：' + res.longitude);
							
							this.form.address = res.name
							this.form.lat = res.latitude
							this.form.lng = res.longitude
							
							// 逆地理编码
							this.loading = true
							const key = 'd1a7ea2dc24fa8ae4b0b10eac185ad5d'
							wx.request({
								url: `https://restapi.amap.com/v3/geocode/regeo?location=${res.longitude},${res.latitude}&key=${key}`,
								success: (res) => {
									console.log('regeo',res)
									
									let provinceName = res.data.regeocode.addressComponent.province
									let cityName = res.data.regeocode.addressComponent.city
									let districtName = res.data.regeocode.addressComponent.district
									let townshipName = res.data.regeocode.addressComponent.township
									
									let dataArr = [provinceName,cityName,districtName,townshipName]
									
									if(this.webSetting.city.cityname != cityName){
										uni.showModal({
											title:'提示',
											content: '该地区暂不支持服务'
										})
										return 
									}
									
									// 选中地址后自动选中所在地区
									return new Promise((resolve, reject) => {
										this.$refs.citypicker.getNextAreaData(0).then((rows)=>{
											rows.forEach((item)=>{
												if(item.name == provinceName){
													resolve()
													this.$refs.citypicker.chooseArea(item).then((city)=>{
														city.forEach((cityItem)=>{
															if(cityItem.name == cityName){
																resolve()
																this.$refs.citypicker.chooseArea(cityItem).then((county)=>{
																	county.forEach((countyItem)=>{
																		if(countyItem.name == districtName){
																			resolve()
																			this.$refs.citypicker.chooseArea(countyItem).then((town)=>{
																				this.form.cityid = town.find((item)=>item.name == townshipName)?.id
																				this.form.selectArea = provinceName + '-' + cityName + '-' + districtName + '-' + townshipName
																				this.$forceUpdate()
																			})
																		}else{
																			reject()
																		}
																	})
																})
															}else{
																reject()
															}
														})
													})
												}else{
													reject()
												}
											})
										})
									})
									.then(()=>{
										this.loading = false
										uni.showToast({
											title: '尽量填写详细地址，以便成功回收',
											icon: 'none',
											duration: 3000
										})
									})
									.catch(()=>{
										this.loading = false
										this.form.address = ''
										uni.showModal({
											title:'提示',
											content: '该地区暂不支持服务'
										})
									})
								},
								fail: (err) => {
									console.log('err:',err)
								},
								complete: () => {
									uni.hideLoading()
									this.loading = false
								}
							})
						},
						fail: (err)=>{
							// uni.showModal({
							// 	title: '失败回调',
							// 	content: JSON.stringify(err)
							// })
							console.log('失败回调',err)
						},
						complete: (complete)=>{
							// uni.showModal({
							// 	title: '结束回调',
							// 	content: JSON.stringify(complete)
							// })
							
							console.log('结束回调',complete)
						}
					});
				}
			}
		},
		methods: {
			chooseMap() {
				if (this.form.address == '') {
					this.showmap = true
				}
			},
			radioChange(e) { // 选中某个单选框时，由radio时触发
				// console.log(e);
			},
			radioGroupChange(e) { // 选中任一radio时，由radio-group触发
				console.log(e);
			},
			setDefault(e) { //设置默认地址
				if (e.target.value) {
					this.$u.get('/User/Address/SetDefault?id=' + this.addressId).then((res) => {
						uni.showToast({
							title: res.msg
						})
					})
				}
			},
			del() { //删除地址
				uni.showModal({
					content: '您确定要删除吗？',
					success: (res) => {
						if (res.confirm) {
							this.$u.get('/User/Address/Delete?id=' + this.addressId).then((res) => {
								uni.showToast({
									title: res.msg
								})
								// uni.reLaunch({
								// 	url: '/pages/my/addressSet/addressSet'
								// })
								// uni.navigateBack();
								this.$emit('edit')
							})
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				})
			},
			close(state) {
				this.cityshow = state
			},
			back(){
				this.$emit('back')
			},
			getDetails(id) { //获取用户地址详情
				this.$u.get('/User/Address/Details?id=' + id).then((res) => {
					this.form = res;
					if(this.form.sex == "先生"){
						this.form.sex = 1
					}else{
						this.form.sex = 2
					}
					
					let citypathArr = res.citypath.split(',').filter((item)=>item != '')
					this.form.cityid = citypathArr[citypathArr.length - 1] //获取最后一个cityid
					console.log('获取最后一个cityid',this.form.cityid)
					this.form.selectArea = res.citynames.split(',').join('-') //获取所在地区
					this.isedit = true
				})
			},
			getSelectCity(arr) { //城市选择回调函数
				console.log(arr)
				
				this.cityshow = false
				// this.selectArea = '';
				let cityidArr = [];
				let getArr = arr.filter(n => n.id != 0)
				let areaname = '';
				getArr.forEach((item, index) => {
					if (index == getArr.length - 1) {
						areaname += item.name
					} else {
						areaname += item.name + '-'
					}
					cityidArr.push(item.id);
				});
				if (cityidArr.length > 0)
					// this.form.cityid = cityidArr.join(',');
					this.form.cityid = cityidArr[cityidArr.length - 1];
				if (areaname)
					this.form.selectArea = areaname;
					
				// if(arr.length == 0){
				// 	this.form.cityid = 0
				// 	this.form.selectArea = ''
				// }
			},
			onSubmit(type) {
				let api = ''
				if (type == 'add') { //添加
					api = '/User/Address/Create'
				} else { //修改
					api = '/User/Address/Edit'
				}
				console.log(this.form)
				this.$refs.uForm.validate(valid => {
					if (valid) {
						this.loading = true
						
						this.$u.post(api,{
							id: this.addressId,
							name: this.form.name,
							sex: this.form.sex,
							mobile: this.form.mobile,
							address: this.form.address,
							cityid: this.form.cityid,
							lng: this.form.lng,
							lat: this.form.lat,
						}).then((res)=>{
							this.loading = false
							uni.showToast({
								title: res.msg
							})
							if (this.type == 'add') {
								this.$emit('add')
							}else if(this.type == 'edit'){
								this.$emit('edit')
							}else {
								uni.navigateTo({
									url: '/pages/my/addressSet/addressSet'
								})
							}
						}).catch(()=>{
							this.loading = false
							this.form.address.replace(this.detailsAddress,'')
						})
					} else {
						console.log('验证失败');
					}
				});
			},
			getAddress(item) {
				this.form.address = item.district + item.name
				let location = item.location.split(',')
				this.form.lng = location[0]
				this.form.lat = location[1]

				// this.form.selectArea = item.district

				this.showmap = false
			}
		}
	};
</script>

<style lang="scss" scoped>
	::v-deep{
		.line {
			color: $u-light-color;
			font-size: 28rpx;
		}
	} 

	.wrap {
		background-color: #f2f2f2;

		.top {
			background-color: #ffffff;
			border-top: solid 2rpx $u-border-color;
			padding: 22rpx;

			.item {
				display: flex;
				font-size: 32rpx;
				line-height: 100rpx;
				align-items: center;
				border-bottom: solid 2rpx $u-border-color;

				.left {
					width: 180rpx;
				}

				input {
					text-align: left;
				}
			}

			.address {
				textarea {
					width: 464rpx;
					height: 160rpx;
					background-color: #f9f9f9;
					line-height: 60rpx;
					padding: 20rpx;
					border-radius: 10rpx;
					font-size: 28rpx;
					border: 1px solid #ededed;
				}
			}

			.site-clipboard {
				padding-right: 40rpx;

				textarea {
					// width: 100%;
					height: 150rpx;
					background-color: #f7f7f7;
					line-height: 60rpx;
					margin: 40rpx auto;
					padding: 20rpx;
				}

				.clipboard {
					display: flex;
					justify-content: center;
					align-items: center;
					font-size: 26rpx;
					color: $u-tips-color;
					height: 80rpx;

					.icon {
						margin-top: 6rpx;
						margin-left: 10rpx;
					}
				}
			}

			.textarea-box {
				display: flex;
				width: 100%;

				.textarea-bg {
					// width: 100%;
					// background-color: $u-bg-color;
				}
				
				.address{
					width: 420rpx
				}
			}
		}

		.bottom {
			margin-top: 20rpx;
			padding: 40rpx;
			padding-right: 0;
			background-color: #ffffff;
			font-size: 28rpx;

			.tag {
				display: flex;

				.left {
					width: 160rpx;
				}

				.right {
					display: flex;
					flex-wrap: wrap;

					.tags {
						width: 140rpx;
						padding: 16rpx 8rpx;
						border: solid 2rpx $u-border-color;
						text-align: center;
						border-radius: 50rpx;
						margin: 0 10rpx 20rpx;
						display: flex;
						font-size: 28rpx;
						align-items: center;
						justify-content: center;
						color: $u-content-color;
						line-height: 1;
					}

					.plus {
						//padding: 10rpx 0;
					}
				}
			}

			.default {
				// margin-top: 50rpx;
				display: flex;
				justify-content: space-between;
				border-bottom: solid 2rpx $u-border-color;
				line-height: 64rpx;

				.tips {
					font-size: 24rpx;
				}

				.right {}
			}
		}
	}
</style>
